/**
 * Created by Mak on 16/11/18.
 */
import Vue from 'vue'
// 递归实现深拷贝 (为了解决循环引用和相同引用、不同类型的深拷贝)
export function isObject(obj) {  // 判断类型
  return obj !== null && typeof obj === 'object'
}
//通过闭包维护一个变量，变量中储存已经遍历过的对象
//每次递归时判断当前的参数是否已经存在于变量中，如果已经存在，就说明已经递归过该变量，就可以停止这次递归并返回上次递归该变量时的返回值
export function _deepClone(obj){
  let visitedObjs = [];
  function baseClone(target){
    if(!isObject(target)) return target
    for(let i = 0; i < visitedObjs.length; i++){
      if(visitedObjs[i].target === target){
        return visitedObjs[i].result;
      }
    }
    let result = Array.isArray(target) ? [] : {}
    visitedObjs.push({ target, result })
    const keys = Object.keys(target);
    for(let i = 0, len = keys.length; i < len; i++) {
      result[keys[i]] = baseClone(target[keys[i]])
    }
    return result
  }
  return baseClone(obj);
}
//**将字符串用js按大写字母拆分，然后以下划线_拼接并转换成小写返回 用作table排序prop格式化 */
export function strsplit(str){
  let strProp = str.split(/(?=[A-Z])/);
  return strProp.join("_").toLowerCase();
}

//根据起始日期和结束日期计算天数
export function  DateDiff(sDate1,  sDate2){
  var  oDate1,  oDate2,  iDays
  oDate1  =  new  Date(sDate1.substring(4,6)  +  '-'  + sDate1.substring(6)  +  '-'  +  sDate1.substring(0,4));
  oDate2  =  new  Date(sDate2.substring(4,6)  +  '-'  + sDate2.substring(6)  +  '-'  +  sDate2.substring(0,4));
  iDays  =  parseInt(Math.abs(oDate1  -  oDate2) / 1000 / 60 / 60 /24);
  return  iDays;
}

/**
  * 获取上一个月
  *
  * @date 格式为yyyy-mm-dd的日期，如：2021-02-25
*/
export function getPreMonth(date){
            var arr = date.split('-');
            var year = arr[0]; //获取当前日期的年份
            var month = arr[1]; //获取当前日期的月份
            var day = arr[2]; //获取当前日期的日
            var days = new Date(year, month, 0);
            days = days.getDate(); //获取当前日期中月的天数
            var year2 = year;
            var month2 = parseInt(month) - 1;
            if (month2 == 0) {
                year2 = parseInt(year2) - 1;
                month2 = 12;
            }
            var day2 = day;
            var days2 = new Date(year2, month2, 0);
            days2 = days2.getDate();
            if (day2 > days2) {
                day2 = days2;
            }
            if (month2 < 10) {
                month2 = '0' + month2;
            }
            var t2 = year2 + '-' + month2;
            t2 = day2 ? t2 + '-' + day2 : t2;
            return t2;
}

export function GetChinese(strValue) { // 只提取汉字
  if (strValue !== null && strValue !== '') {
    const reg = /[\u4e00-\u9fa5]/g;
    return strValue.match(reg).join('');
  }
  return '';
}

export function GetaZ(str){    // 提取英文
  if(str !== null && str !== ''){
    const reg = /[a-zA-Z]/g
    return str.match(reg).join('')
  }
  return ''
}

export function trim(char, type) {  // 字符串处理
  if (char) {
    if (type == 'left') {
      return this.replace(new RegExp('^\\' + char + '+', 'g'), '');
    } else if (type == 'right') {
      return this.replace(new RegExp('\\' + char + '+$', 'g'), '');
    }
    return this.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
  }
  return this.replace(/^\s+|\s+$/g, '');
};


export function parseTime(time, cFormat) {
  if (!time) {
    return null
  }
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

// 格式化时间
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

// 各种数据类型转字符串
export function parseValue(val) {
  if (typeof val === 'string') {
    return val
  } else if (val instanceof Array) {
    return val.join(',')
  } else if (val instanceof Date) {
    return parseTime(val)
  } else {
    return val
  }
}

/**
 *get getByteLen
 * @param {Sting} val input value
 * @returns {number} output value
 */
export function getByteLen(val) {
  let len = 0
  for (let i = 0; i < val.length; i++) {
    if (val[i].match(/[^\x00-\xff]/gi) != null) {
      len += 1
    } else {
      len += 0.5
    }
  }
  return Math.floor(len)
}
// js中国标准时间转换成datetime格式
export function formatData(time, format) {
  var t = new Date(time);
  var tf = function (i) { return (i < 10 ? '0' : '') + i };
  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
    switch (a) {
      case 'yyyy':
        return tf(t.getFullYear());
        break;
      case 'MM':
        return tf(t.getMonth() + 1);
        break;
      case 'mm':
        return tf(t.getMinutes());
        break;
      case 'dd':
        return tf(t.getDate());
        break;
      case 'HH':
        return tf(t.getHours());
        break;
      case 'ss':
        return tf(t.getSeconds());
        break;
    }
  });
}

export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"') +
    '"}'
  )
}

// 设置时间
export function setDefaultTime(time, num, type) {
  let time_num;
  if (type == 'discountId') {
    time = time.substr(0, 19)
    var newstr = time.replace(/-/g, '/');
    var newstrDate = new Date(newstr);
    var time_str = newstrDate.getTime().toString();
    let nums = num ? (num * 60 * 60 * 1000) : 0
    time_num = (Number(time_str) + nums)
  } else {
    time_num = new Date().getTime() + (num ? (num * 60 * 60 * 1000) : 0);
  }
  let d = new Date(time_num);
  let theMonth = d.getMonth() + 1;
  let theDate = d.getDate();
  let theHours = d.getHours();
  let theMinutes = d.getMinutes();
  if (theMonth < 10) {
    theMonth = '0' + theMonth
  }
  if (theDate < 10) {
    theDate = '0' + theDate
  }
  if (theHours < 10) {
    theHours = '0' + theHours
  }
  if (theMinutes < 10) {
    theMinutes = '0' + theMinutes
  }
  let date = d.getFullYear() + '-' + theMonth + '-' + theDate
  let timeHours = theHours + ':' + theMinutes
  let Spare = date + ' ' + timeHours
  return Spare
}

// 判断字符串是否包含某字符串并且转换带标签
export function isContains(str, substr) {
  let strboxs = str;
  if (str) {
    strboxs = strboxs.replace(/\n/g, "<br/>")
    strboxs = strboxs.replace(/\r\n/g, "<br/>")
    // strboxs = strboxs.replace(/\s+/g,"<br/>")
  }
  return strboxs
}

// 判断是是否为json字符串
export function isJSON(str) {
  if (typeof str == 'string') {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      console.log('error：' + str + '!!!' + e);
      return false;
    }
  }
}

// 数组去重
export function deduplicationList(person) {
  let obj = {};
  let peon = person.reduce((cur, next) => {
    obj[next.sku] ? "" : obj[next.sku] = true && cur.push(next);
    return cur;
  }, [])
  return peon
}

// 搜索数组返回新数组
export function inArrayList(list, arr) {
  let nerList = [];
  list.forEach(item => {
    arr.forEach(kitm => {
      if (kitm == item.sku) {
        nerList.push(item)
      }
    })
  })
  return nerList
}

export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**绑定数据**/
export function bindingBean(T, Y) {
  var _this = this;
  if (!myTrim(T) && !myTrim(Y)) {
    for (var key in T) {
      var val = Y[key]
      if (!myTrim(val)) {
        T[key] = typeof val === 'object' ? this.clone(val) : String(val)
      }
    }
  }
  return T
}

// 对象合并
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

export const pickerOptions = [
  {
    text: '今天',
    onClick(picker) {
      const end = new Date()
      const start = new Date(new Date().toDateString())
      end.setTime(start.getTime())
      picker.$emit('pick', [start, end])
    }
  },
  {
    text: '最近一周',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
      picker.$emit('pick', [start, end])
    }
  },
  {
    text: '最近一个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      picker.$emit('pick', [start, end])
    }
  },
  {
    text: '最近三个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      picker.$emit('pick', [start, end])
    }
  }
]

export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

export function percentage(num) {
  return parseFloat(num / 100).toFixed(2) + '%'
}

export function percentage2(num) {
  return parseFloat(num * 100).toFixed(0) + '%'
}

export function generateUUID() {
  var d = new Date().getTime()
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
  })
  return uuid
}

export function myTrim(val) {
  if (val === undefined) {
    return val
  }
  const val2 = val + ''
  return val2.replace(/(^\s*)|(\s*$)/g, '')
}
export function getQueryString(url, name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = url.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}

export function judgeUrlIsImage(url) {
  if (url.indexOf('.png') > -1 || (url.indexOf('.PNG') > -1 ||
    url.indexOf('.jpg') > -1 || url.indexOf('.JPG') > -1 ||
    url.indexOf('.jpeg') > -1 || url.indexOf('.JPEG') > -1 ||
    url.indexOf('.bmp') > -1 || url.indexOf('.BMP') > -1) ||
    url.indexOf('.gif') > -1 || url.indexOf('GIF') > -1) {
    return true
  }
  return false
}
// 去除特殊符号及空格
export function excludeSpecial(str) {
  // 去掉转义字符
  // var reg = new RegExp("[~#^$@%&!?%*]", 'g');

  // str = str.replace(/[\'\"\\\/\b\f\n\r\t]/g, '');
  // // 去掉特殊字符
  // str = str.replace(/[\@\#\$\%\^\&\*\{\}\:\"\L\<\>\?]/);
  str = str.replace('^[0-9a-zA-Z]+/ig', "");
  return str
}
export function isBlank(str) {
  if (str === undefined || myTrim(str) === '') {
    return true
  }
  return false
}
export function closeClick(state) {
  setTimeout(() => {
    var userAgent = navigator.userAgent
    if (userAgent.indexOf('Firefox') !== -1 || userAgent.indexOf('Chrome') !== -1) {
      if (state !== 1) {
        window.parent.opener.location.reload()
      }
      window.location.href = 'about:blank'
      window.close()
    } else {
      if (state !== 1) {
        window.parent.opener.location.reload()
      }
      window.location.href = 'about:blank'
      window.close()
    }
    parent.location.reload()
  }, 1000)
}
// 获取缩略图
export function getMinPicture(src) {
  if (src) {
    if (src.indexOf('kuaxun') === -1) {
      return src
    }
    if (src.indexOf('!min') > -1) {
      return src
    }
    if (src.indexOf('!') > -1) {
      src = src.substr(0, src.indexOf('!'))
    }
    return src + '!min'
  }
}
// loading
export function submitloadingFun() {
  const submitloading = Vue.prototype.$loading({
    lock: true,
    text: '数据加载中，请稍后...',
    spinner: 'el-icon-loading'
  })
  return submitloading
}

// 下载
export function forceDownload(url, filenname) {
  var a = document.createElement('a')
  a.download = filenname
  a.target = '_blank'
  a.href = '//' + document.domain + '/' + url
  console.log(a.href)
  a.click()
}

// 获取url传参
export function getRequest() {
  var arr = location.href.split('?')
  console.log(arr)
  var strs = []
  var url = arr[arr.length - 1] // 获取url中"?"符后的字串
  var theRequest = {}
  // if (url.indexOf('?') !== -1) {
  var str = url.substr(0)
  strs = str.split('&')
  for (var i = 0; i < strs.length; i++) {
    theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
  }
  // }
  return theRequest
}
